package com.zjl.core.servlet;

import ch.qos.logback.ext.spring.web.LogbackConfigListener;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

/**
 * @author : zhangjl
 * @Description : web配置类。程序的入口
 * WebApplicationInitializer类是Spring提供用来配置Servlet3.0+配置的接口，从而实现了代替web.xml的位置。
 * 实现此接口将会自动被SpringServletContainerInitializer获取到，SpringServletContainerInitializer用来启动Servlet3.0容器。
 * 容器启动时会自动扫描当前服务中ServletContainerInitializer的实现类，并调用其onStartup方法，
 * 其参数Set<Class<?>> c，可通过在实现类上声明注解javax.servlet.annotation.HandlesTypes(xxx.class)注解自动注入
 * ，@HandlesTypes会自动扫描项目中所有的xxx.class的实现类，并将其全部注入Set。
 *
 * @Created : 2018-04-26 10:19
 **/
public class MyWebAppInitializer implements WebApplicationInitializer {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyWebAppInitializer.class);

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        LOGGER.info("WebApplicationInitializer start, servlet:{}", JSON.toJSONString(servletContext));
        System.out.println("WebApplicationInitializer start ");
        //添加日志打印
        servletContext.setInitParameter("logbackConfigLocation", "classpath:logback.xml");
        servletContext.addListener(LogbackConfigListener.class);

        //引入spring配置文件
        XmlWebApplicationContext context = new XmlWebApplicationContext();
        //此路径为打包后的文件
        context.setConfigLocation("classpath:spring.xml");
        ContextLoaderListener contextLoaderListener = new ContextLoaderListener(context);
        servletContext.addListener(contextLoaderListener);

        //设置spring 拦截器 DispatchServlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
        dispatcherServlet.setDispatchOptionsRequest(true);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        //可设置多个
        dispatcher.addMapping("/");
        dispatcher.setAsyncSupported(true);

        FilterRegistration.Dynamic shiroFilter = servletContext.addFilter("shiroFilter", DelegatingFilterProxy.class);
        shiroFilter.setInitParameter("argetFilterLifecycl", "true");
        shiroFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
        shiroFilter.setAsyncSupported(true);
        System.out.println("WebApplicationInitializer end ");
    }
}
